package flex.cc.medical.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.medical.dao.RightDao;
import flex.cc.medical.dto.entity.RightEntity;
import flex.cc.medical.service.RightService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.util.SdSignUtil;
import flex.cc.util.APIConfigUtil;

/**
*
* @author R
* 2021年12月15日 下午14:35:19
* @desc 统一发券业务流程实现层
*/
@Service("rightService")
@Transactional(rollbackFor = Exception.class)
public class RightServiceImpl implements RightService {
	private static final Logger logger = LoggerFactory.getLogger(RightServiceImpl.class);
	
    @Autowired
    private RightDao rightDao;
    @Autowired
    private StoreCouponDao storeCouponDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;
	
//    @Value("${api.config.appCode}")
//    private String appCode;
//    @Value("${api.config.appKey}")
//    private String appKey;
    
    /**
     * @description 处理医护合作方回传的权益状态报文
     * @param requestBodyMap 请求体
     * @return  
    */
	@Override
	public JSONObject handleRight(Map<String, Object> requestBodyMap) {
		JSONObject jsonResult = new JSONObject();
		RightEntity rightEntity = new RightEntity();
    	//权益流水id
    	String flowId = PublicUtil.isNotEmpty(requestBodyMap.get("flowId")) ? requestBodyMap.get("flowId").toString() : null;
    	if(flowId == null){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口请求报文中权益流水id为空，无法进行验签");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "权益流水id为空，无法进行验签");
            return jsonResult;
    	}
    	String sign = PublicUtil.isNotEmpty(requestBodyMap.get("sign")) ? requestBodyMap.get("sign").toString() : null; 
    	if(sign == null){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口请求报文中签名为空，无法进行验签");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "签名为空，无法进行验签");
            return jsonResult;
    	}
    	//卡券编码
    	String couponNum = PublicUtil.isNotEmpty(requestBodyMap.get("cardId")) ? requestBodyMap.get("cardId").toString() : null;
    	if(couponNum == null){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口请求报文中卡券编码为空");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "卡券编码不能为空");
            return jsonResult;
    	}
    	Map<String, Object> params = new HashMap<String, Object>();
		params.put("couponNum", couponNum);
		StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(params);
		String provider = couponEntity.getServer();
		String appCode = apiConfigUtil.getApiConfig(provider, "medical_code");
		String appKey = apiConfigUtil.getApiConfig(provider, "medical_key");
    	/** 验签开始**/
    	//生成签名加密前的签名字符串
    	String preSignStr = "appCode="+appCode+"&appkey="+appKey+"&flowId="+flowId;
    	//加密后的签名字符串
    	String sufSignStr = "";
    	try {
    		sufSignStr = SdSignUtil.MD5(preSignStr);
		} catch (Exception e) {
			//返回发券失败异常信息
    		logger.error("回写权益状态接口签名加密异常");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "签名加密异常");
            return jsonResult;
		}
    	if(!sign.equals(sufSignStr)){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口验签失败     sign="+sign+"    sufSignStr="+sufSignStr);
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "回写权益状态接口验签失败");
            return jsonResult;
    	}
    	/** 验签结束**/
    	
    	
    	//用户权益id
    	String userRightId = PublicUtil.isNotEmpty(requestBodyMap.get("userRightId")) ? requestBodyMap.get("userRightId").toString() : null;
    	if(userRightId == null){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口请求报文中用户权益id为空");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "用户权益id不能为空");
            return jsonResult;
    	}
    	
    	//权益id
    	String rightId = PublicUtil.isNotEmpty(requestBodyMap.get("rightId")) ? requestBodyMap.get("rightId").toString() : null;
    	if(rightId == null){
    		//返回发券失败异常信息
    		logger.error("回写权益状态接口请求报文中权益id为空");
    		jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "权益id不能为空");
            return jsonResult;
    	}
    	rightEntity.setCouponNum(couponNum);
    	rightEntity.setFlowId(flowId);
    	rightEntity.setUserRightId(userRightId);
    	rightEntity.setRightId(rightId);
    	
    	//附加信息
    	String extraInfo = PublicUtil.isNotEmpty(requestBodyMap.get("extraInfo")) ? requestBodyMap.get("extraInfo").toString() : null;
    	rightEntity.setExtraInfo(extraInfo);
    	//服务项目
    	String serviceName = PublicUtil.isNotEmpty(requestBodyMap.get("serviceName")) ? requestBodyMap.get("serviceName").toString() : null;
    	rightEntity.setServiceName(serviceName);
    	//预约时间
    	String appointDate = PublicUtil.isNotEmpty(requestBodyMap.get("appointDate")) ? requestBodyMap.get("appointDate").toString() : null;
    	rightEntity.setAppointDate(appointDate);
    	//服务方法
    	String serveType = PublicUtil.isNotEmpty(requestBodyMap.get("serveType")) ? requestBodyMap.get("serveType").toString() : null;
    	rightEntity.setServeType(serveType);
    	//服务地址
    	String serveAddress = PublicUtil.isNotEmpty(requestBodyMap.get("serveAddress")) ? requestBodyMap.get("serveAddress").toString() : null;
    	rightEntity.setServeAddress(serveAddress);
    	//服务状态
    	String serveStatus = PublicUtil.isNotEmpty(requestBodyMap.get("serveStatus")) ? requestBodyMap.get("serveStatus").toString() : null;
    	rightEntity.setServeStatus(serveStatus);
    	//取消类型
    	String cancelType = PublicUtil.isNotEmpty(requestBodyMap.get("cancelType")) ? requestBodyMap.get("cancelType").toString() : null;
    	rightEntity.setCancelType(cancelType);
    	//业务单字段实体
    	String businessField = PublicUtil.isNotEmpty(requestBodyMap.get("businessField")) ? requestBodyMap.get("businessField").toString() : null;
    	if(businessField != null){
    		JSONObject businessBody = JSONObject.parseObject(businessField);
            Map<String, Object> businessBodyMap = businessBody.toJavaObject(Map.class);
          //申请医院
        	String applyHospital = PublicUtil.isNotEmpty(businessBodyMap.get("applyHospital")) ? businessBodyMap.get("applyHospital").toString() : null;
        	rightEntity.setApplyHospital(applyHospital);
        	//申请科室
        	String applyDepartment = PublicUtil.isNotEmpty(businessBodyMap.get("applyDepartment")) ? businessBodyMap.get("applyDepartment").toString() : null;
        	rightEntity.setApplyDepartment(applyDepartment);
        	//申请护理天数
        	String applyNursingDays = PublicUtil.isNotEmpty(businessBodyMap.get("applyNursingDays")) ? businessBodyMap.get("applyNursingDays").toString() : null;
        	rightEntity.setApplyNursingDays(applyNursingDays);
        	//申请护理等级
        	String applyNursingRank = PublicUtil.isNotEmpty(businessBodyMap.get("applyNursingRank")) ? businessBodyMap.get("applyNursingRank").toString() : null;
        	rightEntity.setApplyNursingRank(applyNursingRank);
        	//意向医生
        	String doctorName = PublicUtil.isNotEmpty(businessBodyMap.get("doctorName")) ? businessBodyMap.get("doctorName").toString() : null;
        	rightEntity.setDoctorName(doctorName);
        	//疾病名称
        	String applyIllness = PublicUtil.isNotEmpty(businessBodyMap.get("applyIllness")) ? businessBodyMap.get("applyIllness").toString() : null;
        	rightEntity.setApplyIllness(applyIllness);
        	//疾病备注
        	String illnessNote = PublicUtil.isNotEmpty(businessBodyMap.get("illnessNote")) ? businessBodyMap.get("illnessNote").toString() : null;
        	rightEntity.setIllnessNote(illnessNote);
        	//医保卡号
        	String medicareCard = PublicUtil.isNotEmpty(businessBodyMap.get("medicareCard")) ? businessBodyMap.get("medicareCard").toString() : null;
        	rightEntity.setMedicareCard(medicareCard);
        	//诉求描述
        	String gappealDesc = PublicUtil.isNotEmpty(businessBodyMap.get("gappealDesc")) ? businessBodyMap.get("gappealDesc").toString() : null;
        	rightEntity.setGappealDesc(gappealDesc);
        	//是否可预约专家号
        	String isExpert = PublicUtil.isNotEmpty(businessBodyMap.get("isExpert")) ? businessBodyMap.get("isExpert").toString() : null;
        	rightEntity.setIsExpert(isExpert);
        	//邮寄地址
        	String mailingAddress = PublicUtil.isNotEmpty(businessBodyMap.get("mailingAddress")) ? businessBodyMap.get("mailingAddress").toString() : null;
        	rightEntity.setMailingAddress(mailingAddress);
        	//联系人
        	String contactName = PublicUtil.isNotEmpty(businessBodyMap.get("contactName")) ? businessBodyMap.get("contactName").toString() : null;
        	rightEntity.setContactName(contactName);
        	//联系电话
        	String contactMobile = PublicUtil.isNotEmpty(businessBodyMap.get("contactMobile")) ? businessBodyMap.get("contactMobile").toString() : null;
        	rightEntity.setContactMobile(contactMobile);
    	}
    	
    	rightEntity.setIsDelete(0);
    	rightEntity.setCreater("system");
    	rightEntity.setCreateTime(new Date());
    	rightEntity.setUpdater("system");
    	rightEntity.setUpdateTime(new Date());
    	
    	rightDao.insertRight(rightEntity);
    	
    	jsonResult.put("resultCode", "00");
		jsonResult.put("resultDesc", "回传权益使用状态成功");
        return jsonResult;
	}

}
